import React from 'react';

import {Cascader, Icon, Button} from 'antd';

import styles from './index.less';

export default class CascaderChooserEx extends React.Component{
  
  state = {
    loading:true,
    value:[]
  }

  cascaderData = null;

  async componentWillMount(){
    //获取并组装数据
    this.cascaderData = await this.props.fetchCascaderOption();

    this.reset();

    this.iemi = this.props.emitter.addListener('onReset', ()=>{this.reset()});
    this.props.emitter.emit('onValueChange', this.props.name, this.props.defaultValue.map(v=>v));

    this.setState({
      loading:false
    })
  }

  
  reset(){
    this.setState({
      value:this.props.defaultValue.map(v=>v)
    })
  }

  componentWillReceiveProps(n){
  }
  
  componentWillUnmount(){
    this.iemi.remove();
  }

  onValueChange(e, idx){
    var value = this.state.value;
    value[idx] = e;

    this.props.emitter.emit('onValueChange', this.props.name, value);

    this.setState({
      value:value
    });

    if (this.props.onValueChange){
      this.props.onValueChange(e, idx);
    }
  }

  deleteChoosen(idx){
    var value = this.state.value;

    value.splice(idx, 1);

    this.props.emitter.emit('onValueChange', this.props.name, value);

    this.setState({
      value:value
    })
  }

  addNewChoosen(){
    var value = this.state.value;
    value.push([
    ]);
    
    this.props.emitter.emit('onValueChange', this.props.name, value);

    this.setState({
      value:value
    });

  }

  render(){

    if (this.state.loading){
      return <div>
      </div>
    }else{
      return <div>
        {this.state.value.map((v, idx)=>{
          return <div key = {idx}>
            <Icon type = "delete" onClick = {(e)=>{
              this.deleteChoosen(idx);
            }}/> 
            <Cascader 
              options = {this.cascaderData}
              style = {this.props.style?this.props.style:{width:280}}
              value = {v}
              onChange = {(e)=>{
                console.log(e);
                this.onValueChange(e, idx)
              }} 
            />
          </div>
        })}

        <Button onClick = {(e)=>{
          this.addNewChoosen(e)
        }}>
          添加新商品
        </Button>
      </div>
    }
  }

}